<template>
  <div>
    <n-button size="medium" @click="resetOpen">重置交易密码</n-button>
    <n-modal v-model:show="showMoadl" :mask-closable="false" preset="dialog" title="重置密码">
      <n-form :label-width="80" :model="formValue" :rules="rules" size="medium" ref="formRef">
        <n-form-item label="商户号" path="custNo">
          <n-input
            v-model:value="formValue.custNo"
            placeholder="输入商户号"
            :show-button="false"
            style="width: 100%"
            maxlength="30"
            disabled
          />
        </n-form-item>
        <n-form-item label="邮箱" path="email" style="margin-top: 10px">
          <n-input v-model:value="formValue.email"  maxlength="100" />
        </n-form-item>
        <n-space justify="right">
          <n-form-item>
            <n-space>
              <n-button @click="showMoadl = false" size="medium" strong secondary>取消</n-button>
              <n-button @click="Submit" attr-type="button" size="medium" type="info">确认</n-button>
            </n-space>
          </n-form-item>
        </n-space>
      </n-form>
    </n-modal>
  </div>
</template>
<script lang='ts' setup>
import { ref } from 'vue';
import { useMessage } from 'naive-ui';
import { createStorage } from '@/utils/Storage';

const Storage = createStorage({ storage: localStorage });

import { resetTragePassword } from '@/api/tragePassword/resetTragePassword';

const message = useMessage();

const formRef = ref();

const showMoadl = ref(false); // 是否显示模态框

function resetOpen() {
  clear();
  showMoadl.value = true;
  let custNoValue = Storage.get('custNo');
  formValue.value.custNo = custNoValue;
}
// 表单验证规则
const rules = {
  custNo: {
    required: true,
    message: '请输入姓名',
    trigger: 'blur',
  },
  email: {
    required: true,
    validator(rule, value) {
      if (!value) {
        return new Error('请输入邮箱');
      } else if (!/\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test(value)) {
        return new Error('请输入正确邮箱');
      } else {
        return true;
      }
    },
    trigger: 'blur',
  },
};

const formValue = ref({
  custNo: '',
  email: '',
  type:'C'
});

// 验证结果输出
const Submit = (e) => {
  console.log(formValue.value);
  formRef.value.validate((errors) => {
    if (!errors) {
      resetTragePassword(formValue.value).then((val) => {
        console.log(val);
        if (val.data.sysHead.retCd == '000000') {
          message.success('重置交易密码成功');
          showMoadl.value = false;
        } else {
          message.error('设置交易密码失败');
        }
      });
    } else {
      message.error('重置交易密码失败');
    }
  });
};

const clear = () => {
  formValue.value.custNo = '';
  formValue.value.email = '';
  formValue.value.id = '';
};
</script>